package org.metasketch.editor.toolbox;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.shape.Rectangle;

import org.metasketch.editor.Editor;
import org.metasketch.editor.Project;
import org.metasketch.editor.perspectives.ILayout;
import org.metasketch.editor.perspectives.PerspectiveManager;
import org.metasketch.editor.timeline.SnapshotManager;

public class PerspectiveChooser extends Group implements
		EventHandler<MouseEvent> {

	private Editor editor;
	private ToggleGroup group;
	private ILayout currentLayout;
	Map<String, ILayout> storedLayouts = new HashMap<String, ILayout>();

	// private String currentPerspectiveName;

	public void clear() {

		storedLayouts.clear();
	}

	public PerspectiveChooser(Editor editor) {

		this.editor = editor;

		setup();

	}

	protected void setup() {
		HBox box = new HBox();
		getChildren().add(box);

		String defaultPerspectiveName = SnapshotManager
				.getCurrentPerspectiveName();

		if (defaultPerspectiveName == null)
			defaultPerspectiveName = PerspectiveManager.getDefaultPerspective();

		group = new ToggleGroup();
		List<String> names = PerspectiveManager.getNames();
		for (String name : names) {
			ToggleButton button = new ToggleButton(name);

			button.setMaxWidth(120);
			button.setMinWidth(120);
			button.setPrefWidth(120);

			button.setToggleGroup(group);
			box.getChildren().add(button);
			button.setOnMouseClicked(this);

			if (defaultPerspectiveName.equals(name)) {
				button.setSelected(true);
				setPerspective(name);
			}

		}

		// TextField textField = new TextField();
		// textField.setMinHeight(20);
		// textField.setMinWidth(120);
		//
		// HBox hb = new HBox();
		// hb.getChildren().addAll();
		// box.getChildren().addAll(hb);
	}

	@Override
	public void handle(MouseEvent arg0) {
		ToggleButton toggle = (ToggleButton) arg0.getSource();
		String name = toggle.getText();
		setPerspective(name);
	}

	private void setPerspective(String name) {

		if (storedLayouts.containsKey(name)) {
			currentLayout = storedLayouts.get(name);
		} else {
			currentLayout = PerspectiveManager.getLayout(name);
			currentLayout.setup(editor.getProject());
		}

		editor.resetLayout();

		SnapshotManager.setCurrentPerspectiveName(name);

		currentLayout.apply(editor);

		if (!storedLayouts.containsKey(name))
			storedLayouts.put(name, currentLayout);
	}

	public void setProject(Project project) {
		// TODO Auto-generated method stub
		setup();
	}

}
